import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:file_picker/file_picker.dart';
import 'package:ichinesereader/models/knowledgeword/knowledgeWord.dart';
import 'dart:convert';
import 'package:just_audio/just_audio.dart';
import '../../themes/appTheme.dart';

// ignore: must_be_immutable
class CreateWordCardDialog extends StatefulWidget {
  CreateWordCardDialog(
      {Key? key,
      required this.title,
      required this.wordImageAddress,
      required this.type,
      required this.word})
      : super(key: key);

  String title;
  String wordImageAddress;
  String type;
  KnowledgeWord word;

  @override
  State<StatefulWidget> createState() => _CreateWordCardDialog();
}

class _CreateWordCardDialog extends State<CreateWordCardDialog> {
  List posList = [
    "n.",
    "pron.",
    "adj.",
    "adv.",
    "v.",
    "num.",
    "art.",
    "prep.",
    "conj.",
    "interj.",
  ];

  List<PlatformFile>? _paths;
  String? _extension;
  bool _multiPick = false;
  FileType _pickingType = FileType.image;
  final KnowledgeWordsController controller = Get.find();
  AudioPlayer player = AudioPlayer();
  WordFormModel formModel = WordFormModel();

  @override
  void initState() {
    super.initState();
    this.initForm(formModel.form, widget.word);
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }

  // ignore: unused_element
  void _pickFiles() async {
    // _directoryPath = await FilePicker.platform.getDirectoryPath();
    // print(_directoryPath);
    _paths = (await FilePicker.platform.pickFiles(
      type: _pickingType,
      allowMultiple: _multiPick,
      onFileLoading: (FilePickerStatus status) => print(status),
      allowedExtensions: (_extension?.isNotEmpty ?? false)
          ? _extension?.replaceAll(' ', '').split(',')
          : null,
      withData: false,
      withReadStream: true,
    ))
        ?.files;
    if (_paths != null && _paths!.length > 0) {
      PlatformFile pfile = _paths![0];
      if (pfile.size > 1048576) {
        Get.snackbar('Message'.tr, 'photo size should not more than 1M'.tr,
            backgroundColor: Get.theme.primaryColorDark,
            colorText: Get.theme.primaryColorLight,
            snackPosition: SnackPosition.BOTTOM);
      }
      String fileId = await controller.uploadWordFile(pfile);
      widget.word.image = fileId;
      setState(() {
        widget.wordImageAddress = fileId;
      });
    }
  }

  void generateAndPlay() async {
    print(widget.word.text);
    if (widget.word.text == null) {
      Get.snackbar('Message'.tr, 'word can not be empty'.tr,
          backgroundColor: Get.theme.primaryColorDark,
          colorText: Get.theme.primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      return;
    }
    int len = widget.word.text!.length;
    if (len > 0) {
      String url = await controller.generateAudioByWord(widget.word.text!);
      // player.play(url);
      await player.setAudioSource(AudioSource.uri(Uri.parse(url)));
      player.play();
    }
  }

  void initForm(FormGroup form, KnowledgeWord word) {
    if (word.text == null || word.text?.length == 0) return;
    form.control('word').value = word.text;
    form.control('pinyin').value = word.pinyinNumber;
    form.control('explain').value = word.definition;
    form.control('pos').value = word.category;
    controller.audioAddress = word.audio != null ? word.audio.toString() : '';
    form.control('picture').value = word.image;
    widget.wordImageAddress = word.image != null ? word.image.toString() : '';
    word.example?.forEach((ex) {
      StringBuffer sb = StringBuffer();
      sb.write(ex);
      sb.write('\n');
      form.control('example').value = sb.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];
    var form = formModel.form;
    for (int i = 0; i < posList.length; i++) {
      String? name = posList[i];
      children.add(
        ReactiveRadio(
          formControlName: 'pos',
          value: name,
        ),
      );
      children.add(
        Padding(
          padding: const EdgeInsets.only(right: 30.0),
          child: Text(name.toString(),
              style: TextStyle(
                  color: Get.isDarkMode
                      ? Colors.white
                      : AppTheme.colors.textPrimaryDark)),
        ),
      );
    }

    return Padding(
      padding: const EdgeInsets.all(21.0),
      child: AlertDialog(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              child: Padding(
                padding: const EdgeInsets.only(right: 21.0),
                child: Text(
                  widget.title,
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    letterSpacing: 1,
                    color: Get.isDarkMode
                        ? Get.theme.primaryColorDark
                        : Colors.blueGrey,
                    fontSize: 30,
                    decoration: TextDecoration.underline,
                    decorationStyle: TextDecorationStyle.double,
                    decorationColor: Colors.grey[300],
                  ),
                ),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Icon(Icons.cancel,
                  color: Get.isDarkMode ? Colors.white : Colors.blueGrey),
            ),
          ],
        ),
        backgroundColor:
            Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(6.0),
          ),
        ),
        content: Container(
          // height: 650,
          width: 960,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: [
                ReactiveForm(
                  formGroup: form,
                  child: Column(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'WORD'.tr,
                                      style: TextStyle(
                                          fontSize: 18.0,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : Colors.grey[400]),
                                    ),
                                    ReactiveTextField(
                                      formControlName: 'word',
                                      decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            borderRadius:
                                                BorderRadius.circular(6.0)),
                                        hintText: '幸福',
                                        hintStyle: TextStyle(
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColor
                                              : Colors.grey[300],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: 30,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'PINYIN'.tr,
                                      style: TextStyle(
                                          fontSize: 18.0,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : Colors.grey[400]),
                                    ),
                                    ReactiveTextField(
                                      formControlName: 'pinyin',
                                      decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            borderRadius:
                                                BorderRadius.circular(6.0)),
                                        hintText: 'Xing4;fu2'.tr,
                                        hintStyle: TextStyle(
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColor
                                              : Colors.grey[300],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding:
                                const EdgeInsets.only(top: 21.0, bottom: 9.0),
                            child: Text(
                              'PRONUNCIATION'.tr,
                              style: TextStyle(
                                  fontSize: 18.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.grey[400]),
                            ),
                          ),
                          Row(
                            children: [
                              ElevatedButton.icon(
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      Get.isDarkMode
                                          ? Colors.white
                                          : AppTheme.colors.addBtn),
                                ),
                                icon: Icon(Icons.arrow_right,
                                    size: 30.0,
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Get.theme.primaryColorLight),
                                label: Text(
                                  "Play",
                                  style: TextStyle(
                                      fontSize: 15.0,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight),
                                ),
                                onPressed: () async {
                                  if (controller.audioAddress != '') {
                                    await player.setAudioSource(AudioSource.uri(
                                        Uri.parse(controller.audioAddress)));
                                    player.play();
                                  } else {
                                    Get.snackbar('Message'.tr,
                                        'please generate or record audio'.tr,
                                        backgroundColor:
                                            Get.theme.primaryColorDark,
                                        colorText: Get.theme.primaryColorLight,
                                        snackPosition: SnackPosition.BOTTOM);
                                  }
                                },
                              ),
                              SizedBox(
                                width: 12,
                              ),
                              ElevatedButton(
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(
                                      Get.isDarkMode
                                          ? Colors.white
                                          : AppTheme.colors.purpleBtn),
                                ),
                                // color: Get.isDarkMode
                                //     ? Colors.white
                                //     : AppTheme.colors.purpleBtn,
                                // textColor: Get.isDarkMode
                                //     ? Colors.black
                                //     : Get.theme.primaryColorLight,
                                onPressed: () {
                                  print(form.control("word").value);
                                  this.generateAndPlay();
                                },
                                child: Text(
                                  'Auto Generate'.tr,
                                  style: TextStyle(
                                      fontSize: 16.0,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.white),
                                ),
                              ),

                              // MaterialButton(
                              //     color: Get.isDarkMode
                              //         ? (Color(0xff444444))
                              //         : (Colors.white),
                              //     textColor: Get.isDarkMode
                              //         ? (Color(0xffcccccc))
                              //         : Theme.of(context).primaryColorDark,
                              //     onPressed: () {
                              //       Navigator.of(context).pop();
                              //     },
                              //     child: Text('Record'.tr))
                            ],
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding:
                                const EdgeInsets.only(top: 21.0, bottom: 9.0),
                            child: Text(
                              'POS'.tr,
                              style: TextStyle(
                                  fontSize: 18.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.grey[400]),
                            ),
                          ),
                          Row(
                            children: [
                              Expanded(
                                  child: SingleChildScrollView(
                                scrollDirection: Axis.horizontal,
                                child: Row(
                                  children: children,
                                ),
                              ))
                            ],
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding:
                                const EdgeInsets.only(top: 21.0, bottom: 9.0),
                            child: Text(
                              'EXPLAIN'.tr,
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Colors.grey[400],
                              ),
                            ),
                          ),
                          ReactiveTextField(
                            formControlName: 'explain',
                            maxLines: 3,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              hintText: 'Word Example'.tr,
                              hintStyle: TextStyle(
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColor
                                    : Colors.grey[300],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding:
                                const EdgeInsets.only(top: 12.0, bottom: 9.0),
                            child: Text(
                              'EXAMPLE'.tr,
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Colors.grey[400],
                              ),
                            ),
                          ),
                          ReactiveTextField(
                            formControlName: 'example',
                            maxLines: 3,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8.0)),
                              hintText: '回车换行后生成新的实例'.tr,
                              hintStyle: TextStyle(
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[300]),
                            ),
                          )
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding:
                                const EdgeInsets.only(top: 21.0, bottom: 9.0),
                            child: Text(
                              'PICTURE'.tr,
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Colors.grey[400],
                              ),
                            ),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(bottom: 9.0),
                                child: DebouncedMaterialButton(
                                    debounceTimeMs: 1200,
                                    color: Get.isDarkMode
                                        ? Colors.white
                                        : AppTheme.colors.orangeBtn,
                                    textColor: Get.isDarkMode
                                        ? Colors.black
                                        : AppTheme.colors.lightOrange,
                                    onPressed: () {
                                      _pickFiles();
                                    },
                                    child: Text('Upload'.tr)),
                              ),
                              Container(
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.blueGrey.withOpacity(0.3),
                                      offset: const Offset(
                                        1.0,
                                        1.0,
                                      ),
                                      blurRadius: 6.0,
                                      spreadRadius: 1.0,
                                    ), //BoxShadow
                                    BoxShadow(
                                      color: Colors.white,
                                      offset: const Offset(0.0, 0.0),
                                      blurRadius: 0.0,
                                      spreadRadius: 0.0,
                                    ),
                                  ],
                                ),
                                child: Image.network(
                                  widget.wordImageAddress,
                                  // 'https://resources.ichinesereader.com/media/knowledgelib/cust/cd1ee2a9-45e7-400c-bed7-b4449fed6af9.jpeg',
                                  height: 10.0,
                                  width: 10,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Image.asset(
                                        'assets/images/imagenotavailable.png',
                                        height: 150.0,
                                        width: 150,
                                        fit: BoxFit.cover);
                                  },
                                ),
                              ),
                            ],
                          ),
                          ReactiveFormConsumer(
                            builder: (context, form, child) {
                              widget.word.pinyin = form.control("pinyin").value;
                              widget.word.text = form.control("word").value;
                              widget.word.category = form.control("pos").value;
                              widget.word.definition =
                                  form.control("explain").value;

                              LineSplitter ls = new LineSplitter();

                              if (form.control("example").value != null) {
                                widget.word.example =
                                    ls.convert(form.control("example").value);
                              }

                              return Padding(
                                padding: const EdgeInsets.only(top: 18.0),
                                child: Row(
                                  children: [
                                    Spacer(),
                                    Container(
                                      width: 210.0,
                                      height: 45.0,
                                      child: DebouncedMaterialButton(
                                        color: Get.isDarkMode
                                            ? (Colors.white)
                                            : Theme.of(context).primaryColor,
                                        textColor: Get.isDarkMode
                                            ? (Colors.black)
                                            : Theme.of(context)
                                                .primaryColorLight,
                                        onPressed: () {
                                          LineSplitter ls = new LineSplitter();

                                          if (form.control("example").value !=
                                              null) {
                                            widget.word.example = ls.convert(
                                                form.control("example").value);
                                            for (String exam
                                                in widget.word.example!) {
                                              print(exam);
                                            }
                                          }

                                          widget.word.audio =
                                              controller.audioAddress;
                                          if (widget.word.audio == null) {
                                            Get.snackbar('Message'.tr,
                                                'please generate word audio'.tr,
                                                backgroundColor:
                                                    Get.theme.primaryColorDark,
                                                colorText:
                                                    Get.theme.primaryColorLight,
                                                snackPosition:
                                                    SnackPosition.BOTTOM);
                                            return;
                                          }

                                          if (widget.word.pinyin == null) {
                                            Get.snackbar('Message'.tr,
                                                'please input word pinyin'.tr,
                                                backgroundColor:
                                                    Get.theme.primaryColorDark,
                                                colorText:
                                                    Get.theme.primaryColorLight,
                                                snackPosition:
                                                    SnackPosition.BOTTOM);
                                            return;
                                          }

                                          if (widget.word.text == null) {
                                            Get.snackbar('Message'.tr,
                                                'please input word text'.tr,
                                                backgroundColor:
                                                    Get.theme.primaryColorDark,
                                                colorText:
                                                    Get.theme.primaryColorLight,
                                                snackPosition:
                                                    SnackPosition.BOTTOM);
                                            return;
                                          }

                                          if (widget.word.text!.length > 1 &&
                                              !widget.word.pinyin!
                                                  .contains(';')) {
                                            Get.snackbar(
                                                'Message'.tr,
                                                'please input pinyin by format'
                                                    .tr,
                                                backgroundColor:
                                                    Get.theme.primaryColorDark,
                                                colorText:
                                                    Get.theme.primaryColorLight,
                                                snackPosition:
                                                    SnackPosition.BOTTOM);
                                            return;
                                          }

                                          int i = widget.word.pinyin!
                                                  .codeUnitAt(widget
                                                          .word.pinyin!.length -
                                                      1) -
                                              48;
                                          //print(i);
                                          if (i < 1 || i > 4) {
                                            Get.snackbar(
                                                'Message'.tr,
                                                'please input pinyin by format'
                                                    .tr,
                                                backgroundColor:
                                                    Get.theme.primaryColorDark,
                                                colorText:
                                                    Get.theme.primaryColorLight,
                                                snackPosition:
                                                    SnackPosition.BOTTOM);
                                            return;
                                          }

                                          if (controller.currdir.length == 0) {
                                            controller
                                                .fetchKnowledgeFolderTree(true);
                                          }
                                          String? folderId = controller
                                                      .currdir.length >
                                                  0
                                              ? controller.currdir[
                                                  controller.currdir.length - 1]
                                              : '';
                                          if (folderId == '') return;

                                          if (widget.type == 'create') {
                                            controller.createKnowledgeWord(
                                                widget.word,
                                                folderId.toString());
                                          } else {
                                            controller.updateKnowledgeWord(
                                                widget.word);
                                          }

                                          // print(controller
                                          //     .statusMessageResult.value.message);

                                          Navigator.of(context).pop();
                                        },
                                        child: Text(
                                          'Submit'.tr,
                                          style: TextStyle(fontSize: 18.0),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
